﻿using LiveCharts;
using LiveCharts.Configurations;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace DemoSignalR.Client
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private TestSignalRClient testSignalRClient;

        public ChartValues<TestValue> PhaseChartValues { get; set; }
        public float PhaseValue { get; set; }

        private int _index;

        // 当数值被更改时，触发更新
        public int Index
        {
            get { return _index; }
            set
            {
                _index = value;
                Read();
            }
        }

        public MainWindow()
        {
            InitializeComponent();
            var mapper = Mappers.Xy<TestValue>()
                .X(model => model.Index)
                .Y(model => model.Value);
            Charting.For<TestValue>(mapper);
            PhaseChartValues = new ChartValues<TestValue>();

            DataContext = this;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (testSignalRClient == null)
            {
                testSignalRClient = new TestSignalRClient();
                testSignalRClient.RefreshInfos += RefreshInfo;
                testSignalRClient.Start();
                testSignalRClient.Listen();
                testSignalRClient.StartNotify("WPF Client");
            }
        }

        private void RefreshInfo(object obj)
        {
            var testValue = JsonConvert.DeserializeObject<TestValue>(obj.ToString());
            // 更新图表数据
            this.PhaseValue = testValue.Value;
            this.Index = testValue.Index;
        }

        // 更新图表
        private void Read()
        {
            PhaseChartValues.Add(new TestValue
            {
                Index = this.Index,
                Value = this.PhaseValue
            });


            // 限定图表最多只有十五个元素
            if (PhaseChartValues.Count > 20)
            {
                PhaseChartValues.RemoveAt(0);
                //ModulusChartValues.RemoveAt(0);
            }
        }
    }

    public class TestValue
    {
        private int index;
        public int Index { get { return index; } set { index = value; } }

        private float value;
        public float Value { get { return value; } set { this.value = value; } }
    }
}
